<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Model\BotsModel;
use App\Model\OutTradeModel;
use App\Service\BotsService;
use App\Service\SteamService;
use App\Service\LogService;
use App\Jobs\LoginRobotJob;
use App\Service\OutTradeService;


class SendOutTrade extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $signature = 'send:outtrade';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '发送报价.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取准备发起报价的信息
     * @return array
     */
    protected function getOutTradeByReading()
    {
        return OutTradeModel::getOutTradeByReading();
    }

    /**
     * 获取机器人信息
     * @param  int $botId 机器人ID
     * @return array
     */
    protected function getBotsInfoBybotId($botId)
    {
        return BotsModel::getBotsInfoBybotId($botId);
    }

    /**
     * 添加记录
     * @param  string $action 控制器名称
     * @param  int $botId 机器人ID
     * @param  int $steamId STEAMID
     * @param  string $errorMsg 错误信息
     * @return array
     */
    protected function addActionLog($action, $botId, $steamId, $errorMsg)
    {
        return LogService::getInstance()->addActionLog($action, $botId, $steamId, $errorMsg);
    }

    /**
     * 记录报价ID
     * @param  int $outTradeId 报价订单ID
     * @param  int $tradeofferId 报价ID
     * @return bool
     */
    protected function updateOutTradeByOutTradeId($outTradeId, $tradeofferId)
    {
        return OutTradeModel::updateOutTradeByOutTradeId($outTradeId, $tradeofferId);
    }

    /**
     * 修改报价状态
     * @param  int $outTradeId 报价订单ID
     * @param  int $tradeofferStatus 报价状态
     * @return bool
     */
    protected function updateOutTradeState($outTradeId, $tradeofferStatus)
    {
        return OutTradeModel::updateOutTradeState($outTradeId, $tradeofferStatus);
    }

    protected function sendTrade()
    {
        $trades = $this->getOutTradeByReading();
        if (!$trades) {
            echo 'query reading out trade failed' . "\r\n";
            return false;
        }

        foreach ($trades as $trade) {
            $this->sendOutTrade($trade['bot_id'], $trade);
        }

        return true;
    }

    public function sendOutTrade($botId, $order)
    {
        $info = $this->getBotsInfoBybotId($botId);
        if (!$info) {
            echo 'query bots failed, botid: ' . $botId . "\r\n";
            return false;
        }

        $apiKey = $info['apikey'];
        $account = $info['steam_account'];
        $outTradeId = $order['out_trade_id'];
        $tradeMsg = $order['tradeoffer'];

        $steam = BotsService::getInstance()->getLgoinObjByBotId($botId, $account);
        if (!$steam) {
            echo 'query bot object failed, bot_id: ' . $botId . "\r\n";
            return false;
        }

        if ($steam->isLoggedIn()) {
            $tradeOffers = $steam->tradeOffers();
            $trade = $tradeOffers->createTrade($order['steam_id']);
            $trade->setMessage($tradeMsg);

            foreach ($order['out_trade_detail'] as $details) {
                $trade->addMyItem($details['app_id'], $details['context_id'], $details['o_id'], $details['amount']);
            }

            $tradeofferId = $trade->sendWithToken($order['steam_token']);
            if ($error = $trade->getError()) {
                echo 'send trade failed, error:' . $error . "\r\n";
                if ($tradeofferId == 'relogin') {
                    dispatch((new LoginRobotJob($botId))->onQueue(($info['client_no'] ? 'LoginRobotJob_' . $info['client_no'] : 'LoginRobotJob'))->delay(1));
                    return false;
                }

                $status = OutTradeService::getInstance()->getTradeStatusMap($tradeofferId);
                if (!$status) {
                    echo 'undefined trade status, status:' . $status . "\r\n";
                    return false;
                }
                $this->updateOutTradeState($outTradeId, $status);

                return false;
            }

            $res = $this->updateOutTradeByOutTradeId($outTradeId, $tradeofferId);
            if (!$res) {
                echo 'update out trade failed, out_trade_id: ' . $outTradeId . "\r\n";
                return false;
            }
            echo 'send trade offer success' . "\r\n";
        }

        return false;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->sendTrade();
        echo '数据查询完毕!' . "\r\n";
        return false;
    }
}